package ru.pomarshrutu.server.model;

import java.util.ArrayList;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Blob;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Recording {
	public static int MAX_BLOCK_SIZE = 512;

	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Long id;
	
	@Persistent
	private ArrayList<Blob> data;

	private PersistenceManager persistenceManager;
	
	public Recording(byte[] data) {
		setData(data);
	}
	
	public Recording(byte[] data, PersistenceManager pm) {
		this.persistenceManager = pm;
		setData(data);
	}

	public Long getId() {
		return id;
	}

	public void setData(byte[] data) {
		this.data = new ArrayList<Blob>();
		
		for(int i = 0; i < data.length; i += MAX_BLOCK_SIZE) {
			int blockLength = Math.min(data.length - i, MAX_BLOCK_SIZE);
			byte[] block = new byte[blockLength];
			System.arraycopy(data, i, block, 0, blockLength);
			this.data.add(new Blob(block));
			if(persistenceManager != null) persistenceManager.makePersistent(this);
		}
	}
	
	public byte[] getData() {
		if(data.size() == 0) return new byte[0];
		
		byte[] ret = new byte[
		                      (data.size() - 1) * MAX_BLOCK_SIZE + 
		                      data.get(data.size() - 1).getBytes().length //last part may be less
		                      ];
		for(int i = 0; i < data.size(); i++) {
			Blob blob = data.get(i);
			System.arraycopy(blob.getBytes(), 0, ret, i * MAX_BLOCK_SIZE, blob.getBytes().length);
		}
		
		return ret;
	}
	
	public int getNBlocks() {
		return data.size();
	}
}
